<?php
//decode by QQ:270656184 http://www.yunlu99.com/
defined('IN_IA') or exit('Access Denied');

class Bsht_tbkModuleProcessor extends WeModuleProcessor
{
	private $sceneid = 0;
	private $Qrcode = "/addons/bsht_tbk/qrcode/mposter#sid#.jpg";

	private function sendImage($openid, $media_id)
	{
		$data = array("touser" => $openid, "msgtype" => "image", "image" => array("media_id" => $media_id));
		$ret = $this->postRes($this->getAccessToken(), json_encode($data));
		return $ret;
	}

	private function uploadImage($img)
	{
		$this->postText($this->message['from'], '');
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" . $this->getAccessToken() . "&type=image";
		$post = array('media' => '@' . $img);
		load()->func('communication');
		$ret = ihttp_request($url, $post);
		$this->postText($this->message['from'], '');
		$content = @json_decode($ret['content'], true);
		if ($ret['errno'] != 1) {
			return $content['media_id'];
		} else {
			$this->postText($this->message['from'], '获取海报失败，请重试！');
			exit;
		}
	}

	public function respond()
	{
		global $_W, $member, $fans, $settings;
		load()->model('mc');
		$settings = $this->module["config"];
		$rid = $this->rule;
		$poster = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_poster') . " WHERE uniacid = :uniacid order by id asc", array(':uniacid' => $_W['uniacid']));
		$fans = mc_fetch($this->message['from']);
		if (empty($fans['nickname']) || empty($fans['avatar'])) {
			$openid = $this->message['from'];
			$ACCESS_TOKEN = $this->getAccessToken();
			$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$openid}&lang=zh_CN";
			load()->func('communication');
			$json = ihttp_get($url);
			$userInfo = @json_decode($json['content'], true);
			$nickname = $userInfo['nickname'];
			$nickname = $this->emoji($nickname);
			$fans['nickname'] = $nickname;
			$fans['avatar'] = $userInfo['headimgurl'];
		} else {
			$fans['nickname'] = $this->emoji($fans['nickname']);
			if (empty($fans['nickname'])) {
				$fans['nickname'] = '匿名用户';
			}
		}
		if (!empty($poster)) {
			if ($poster['starttime'] > time()) {
				return $this->postText($this->message['from'], $poster['nostarttxt']);
			} elseif ($poster['endtime'] < time()) {
				return $this->postText($this->message['from'], $poster['endtxt']);
			}
		}
		if ($this->message['content'] == '牛贝签到' || $this->message['content'] == 'NB文字签到') {
			$rid = $this->rule;
			$nbqdnum = 'H' . $rid;
			$huod = array();
			$content = $this->message['content'];
			$member = array();
			$member = mc_fetch($fans['uid'], array('nickname', 'credit1'));
			$_W['uid'] = $fans['uid'];
			if (empty($member['nickname'])) {
				$member['nickname'] = $fans['nickname'];
			}
			$today = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
			if (empty($settings['success_msg'])) {
				$settings['success_msg'] = "亲，您好棒！签到成功啦！[签到积分]个积分正在奔赴您的账户！明天再来签到您将能获得[下期积分]个积分！要天天来哦~！请登录会员中心查询。";
			}
			if (empty($settings['continuity_msg'])) {
				$settings['continuity_msg'] = "亲，您太热情了，今天您已经签到过了~明天再来吧~";
			}
			$_W['nbqd']['allnum'] = (int)pdo_fetchcolumn("SELECT sum(num) FROM " . tablename('mc_credits_record') . " WHERE uniacid=:uniacid AND uid=:uid AND module = 'bsht_tbk' ", array(':uniacid' => $_W['uniacid'], ':uid' => $fans['uid']));
			$_W['nbqd']['todaycom'] = pdo_fetch("SELECT COUNT(*) AS a , sum(num) AS b FROM " . tablename('mc_credits_record') . " WHERE uniacid=:uniacid AND module = 'bsht_tbk' AND createtime>=:starttime", array(':uniacid' => $_W['uniacid'], ':starttime' => $today));
			$_W['nbqd']['number'] = 0;
			$_W['nbqd']['total'] = round($member['credit1']);
			$_W['nbqd']['jl'] = 0;
			$nao = intval(date("Hi"));
			$thisw = intval(date("w"));
			$record = (int)pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename('mc_credits_record') . " WHERE uniacid=:uniacid AND uid=:uid AND module = 'bsht_tbk' AND createtime>=:starttime", array(':uniacid' => $_W['uniacid'], ':uid' => $fans['uid'], ':starttime' => $today));
			if (!empty($settings['time']['is']) && ($nao < (int)$settings['time']['a'] || $nao > (int)$settings['time']['e'])) {
				$nbqdtips = '';
				$settings['welcome'] = $settings['time']['t'];
			} elseif (empty($record)) {
				$record = pdo_fetch("SELECT COUNT(*) AS number , num FROM " . tablename('mc_credits_record') . " WHERE uniacid=:uniacid AND uid=:uid AND module = 'bsht_tbk' AND createtime>=:starttime AND createtime<:endtime", array(':uniacid' => $_W['uniacid'], ':uid' => $fans['uid'], ':starttime' => $today - 86400, ':endtime' => $today));
				if (empty($record['number'])) {
					$_W['nbqd']['number'] = max(1, $settings['everyday']);
				} else {
					$_W['nbqd']['number'] = $record['num'] + max(0, $settings['continuity']);
				}
				if ((int)$settings['intup'] > 0 && $_W['nbqd']['number'] > (int)$settings['intup']) {
					$_W['nbqd']['number'] = (int)$settings['intup'];
				}
				mc_credit_update($fans['uid'], 'credit1', $_W['nbqd']['number'], array(0 => 0, 1 => '每日签到奖励【' . $_W['nbqd']['number'] . '】积分', 'bsht_tbk', 0, 0));
				$_W['nbqd']['total'] = round($member['credit1'] + $_W['nbqd']['number']);
				$_W['nbqd']['allnum'] = round($_W['nbqd']['allnum'] + $_W['nbqd']['number']);
				$_W['nbqd']['today'] = $_W['nbqd']['number'];
				$_W['nbqd']['todaycom']['a'] = (int)$_W['nbqd']['todaycom']['a'] + 1;
				$_W['nbqd']['todaycom']['b'] = (int)$_W['nbqd']['todaycom']['b'] + $_W['nbqd']['number'];
				$nbqdtips = $this->nbqdreplace($settings['success_msg']);
			} else {
				$_W['nbqd']['today'] = (int)pdo_fetchcolumn("SELECT num FROM " . tablename('mc_credits_record') . " WHERE uniacid=:uniacid AND uid=:uid AND module = 'bsht_tbk' AND createtime>=:starttime", array(':uniacid' => $_W['uniacid'], ':uid' => $fans['uid'], ':starttime' => $today));
				$nbqdtips = $this->nbqdreplace($settings['continuity_msg']);
			}
			if (!empty($settings['ispaihang']) && $settings['ispaihang'] > 0) {
				$i = 1;
				$b = 'Y年m月d日';
				$c = "分";
				if ($settings['ispaihang'] == '1') {
					$phtj = array(':uniacid' => $_W['uniacid'], ':starttime' => $today);
					$nbqdtips .= "\n今日排行榜";
					$b = 'H:i:s';
				} elseif ($settings['ispaihang'] == '2') {
					$phtj = array(':uniacid' => $_W['uniacid'], ':starttime' => $today - 604800);
					$nbqdtips .= "\n7天排行榜";
				} elseif ($settings['ispaihang'] == '3') {
					$phtj = array(':uniacid' => $_W['uniacid'], ':starttime' => $today - 2592000);
					$nbqdtips .= "\n30天排行榜";
				} elseif ($settings['ispaihang'] == '4') {
					$phtj = array(':uniacid' => $_W['uniacid'], ':starttime' => 0);
					$nbqdtips .= "\n历史排行榜";
				} elseif ($settings['ispaihang'] == '5') {
					$phtj = array(':uniacid' => $_W['uniacid'], ':starttime' => mktime(0, 0, 0, date("m"), 1, date("Y")));
					$nbqdtips .= "\n本月排行榜";
				}
				if (intval($settings['px']) == '1') {
					$px = ' DESC ';
				} else {
					$px = '';
				}
				if ($settings['paihangt'] == '1') {
					$ph = pdo_fetchall("SELECT uid,sum(num) as num,createtime FROM " . tablename('mc_credits_record') . " WHERE uniacid=:uniacid AND module = 'bsht_tbk' AND createtime>=:starttime group by uid ORDER BY num DESC,id " . $px . " LIMIT " . max(3, (int)$settings['paihangs']), $phtj);
					$nbqdtips .= "(按总积分)：\n";
				} elseif ($settings['paihangt'] == '2') {
					$ph = pdo_fetchall("SELECT uid,count(id) as num,max(createtime) as createtime FROM " . tablename('mc_credits_record') . " WHERE uniacid=:uniacid AND module = 'bsht_tbk' AND createtime>=:starttime group by uid ORDER BY num DESC,id " . $px . " LIMIT " . max(3, (int)$settings['paihangs']), $phtj);
					$nbqdtips .= "(按总次数)：\n";
					$c = "次";
				} else {
					$ph = pdo_fetchall("SELECT uid,max(num) as num,createtime FROM " . tablename('mc_credits_record') . " WHERE uniacid=:uniacid AND module = 'bsht_tbk' AND createtime>=:starttime group by uid ORDER BY num DESC,id " . $px . " LIMIT " . max(3, (int)$settings['paihangs']), $phtj);
					$nbqdtips .= "(按单次签)：\n";
				}
				foreach ($ph as $param) {
					$aa = mc_fetch($param['uid']);
					$nbqdtips .= "第" . $i . "名：[" . round($param['num']) . $c . "]" . $aa['nickname'] . "\n";
					$i += 1;
				}
			}
			if (empty($settings['welcome'])) {
				$settings['welcome'] = "亲爱的粉丝，欢迎您签到";
			}
			if (empty($settings['nbqd_diy'])) {
				$settings['nbqd_diy'] = "更多优惠：[模块首页]";
				$nbqd_diy = $this->nbqdreplace($settings['nbqd_diy']);
			} else {
				$nbqd_diy = $this->nbqdreplace($settings['nbqd_diy']);
			}
			$this->postText($this->message['from'], $settings['welcome']);
			return $this->postText($this->message['from'], $nbqdtips . '\n' . $nbqd_diy);
		}
		if ($this->message['content'] == '激活用户') {
			$rid = $this->rule;
			$poster = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_poster') . " WHERE uniacid = :uniacid order by id asc", array(':uniacid' => $_W['uniacid']));
			$newuser = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_user') . " WHERE uniacid = :uniacid and from_user=:from_user", array(':uniacid' => $_W['uniacid'], ':from_user' => $this->message['from']));
			if ($newuser) {
				$this->postText($this->message['from'], "请勿重复激活！");
				exit;
			} else {
				pdo_insert($this->modulename . "_user", array('uid' => $fans['uid'], 'nickname' => $fans['nickname'], 'avatar' => $fans['avatar'], 'pid' => $poster['id'], 'createtime' => time(), 'vtime' => time(), 'ctime' => time(), 'uniacid' => $_W['uniacid'], 'score' => $poster['score'], 'cscore' => $poster['cscore'], 'pscore' => $poster['pscore'], 'from_user' => $this->message['from'], 'openid' => $this->message['from'], 'follow' => 1));
				$this->postText($this->message['from'], "激活成功！");
				exit;
			}
		}
		if ($this->message['msgtype'] == 'event') {
			$scene_id = str_replace('qrscene_', '', $this->message['eventkey']);
			$fans = mc_fetch($this->message['from']);
			if (empty($fans['nickname']) || empty($fans['avatar'])) {
				$openid = $this->message['from'];
				$ACCESS_TOKEN = $this->getAccessToken();
				$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$ACCESS_TOKEN}&openid={$openid}&lang=zh_CN";
				load()->func('communication');
				$json = ihttp_get($url);
				$userInfo = @json_decode($json['content'], true);
				$userInfo['nickname'] = $this->emoji($userInfo['nickname']);
				$fans['nickname'] = $userInfo['nickname'];
				$fans['avatar'] = $userInfo['headimgurl'];
				mc_update($this->message['from'], array('nickname' => $userInfo['nickname'], 'avatar' => $userInfo['avatar']));
			}
			if ($this->message['event'] == 'subscribe') {
				$sy_member = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_user') . " WHERE uniacid = :uniacid and sceneid=:sceneid", array(':uniacid' => $_W['uniacid'], ':sceneid' => $scene_id));
				$member = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_user') . " WHERE uniacid = :uniacid and from_user=:from_user", array(':uniacid' => $_W['uniacid'], ':from_user' => $this->message['from']));
				$noemojinn = $fans['nickname'];
				$noemojinn = $this->emoji($noemojinn);
				if (empty($member)) {
					pdo_insert($this->modulename . "_user", array('uid' => $fans['uid'], 'nickname' => $noemojinn, 'avatar' => $fans['avatar'], 'pid' => $poster['id'], 'createtime' => time(), 'vtime' => time(), 'ctime' => time(), 'helpid' => $sy_member['uid'], 'uniacid' => $_W['uniacid'], 'score' => $poster['score'], 'cscore' => $poster['cscore'], 'pscore' => $poster['pscore'], 'from_user' => $this->message['from'], 'openid' => $this->message['from'], 'follow' => 1));
					$share['id'] = pdo_insertid();
					$share = pdo_fetch('select * from ' . tablename($this->modulename . "_user") . " where id='{$share['id']}'");
					if ($poster['score'] > 0) {
						$info1 = str_replace('#昵称#', $fans['nickname'], $poster['ftips']);
						$info1 = str_replace('#积分#', $poster['score'], $info1);
						if ($poster['score']) {
							mc_credit_update($share['uid'], 'credit1', $poster['score'], array($share['uid'], '关注送积分'));
						}
						$this->postText($this->message['from'], $info1);
					}
					if ($poster['cscore'] > 0) {
						if ($sy_member['status'] == 0) {
							exit;
						}
						$info2 = str_replace('#昵称#', $fans['nickname'], $poster['utips']);
						$info2 = str_replace('#积分#', $poster['cscore'], $info2);
						if ($poster['cscore']) {
							mc_credit_update($sy_member['uid'], 'credit1', $poster['cscore'], array($sy_member['uid'], '1级推广奖励'));
						}
						$this->postText($sy_member['from_user'], $info2);
					}
					if ($poster['pscore'] > 0) {
						$fmember = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_user') . " WHERE uniacid = :uniacid and uid=:uid", array(':uniacid' => $_W['uniacid'], ':uid' => $sy_member['helpid']));
						if ($fmember['status'] == 0) {
							exit;
						}
						if ($fmember) {
							$info3 = str_replace('#昵称#', $fans['nickname'], $poster['utips2']);
							$info3 = str_replace('#积分#', $poster['pscore'], $info3);
							if ($poster['pscore']) {
								mc_credit_update($fmember['uid'], 'credit1', $poster['pscore'], array($fmember['uid'], '2级推广奖励'));
							}
							$this->postText($fmember['from_user'], $info3);
						}
					}
				} else {
					$this->postText($this->message['from'], '亲，您已经是粉丝了，快去生成海报赢取奖励吧');
				}
				return '';
			}
			if ($this->message['event'] == 'SCAN') {
				$jftxt = "积分";
				$msg1 = $fans['nickname'] . "你已经是【" . $_W['account']['name'] . "】的粉丝了，请勿重复扫码！\n\n你当前有" . $fans['credit1'] . "" . $jftxt . "";
				return $this->postText($this->message['from'], $msg1);
			}
		}
		if ($this->message['msgtype'] == 'text' || $this->message['event'] == 'CLICK') {
			$rid = $this->rule;
			$poster = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_poster') . " WHERE uniacid = :uniacid order by id asc", array(':uniacid' => $_W['uniacid']));
			if (!empty($settings['hbsctime'])) {
				$share = pdo_fetch('select * from ' . tablename($this->modulename . "_user") . " where from_user='{$this->message['from']}' and pid='{$poster['id']}' ");
				if ($share['updatetime'] > 0 && time() - $share['updatetime'] < $settings['hbsctime']) {
					if (!empty($settings['hbcsmsg'])) {
						$this->postText($this->message['from'], $settings['hbcsmsg']);
					}
					return '';
					exit();
				}
			}
			$img = $this->createPoster($fans, $poster);
			$this->postText($this->message['from'], '');
			$media_id = $this->uploadImage($img);
			if ($poster['addinfo1']) {
				$info = str_replace('#时间#', date('Y-m-d H:i', time() + 30 * 24 * 3600), $poster['addinfo1']);
				$this->postText($this->message['from'], $info);
			}
			if ($poster['addinfo2']) {
				$msg2 = $poster['addinfo2'];
				if ($poster['rtype'] && $poster['type'] == 2) ;
				$this->postText($this->message['from'], $msg2);
			}
			if ($this->message['checked'] == 'checked') {
				$this->sendImage($this->message['from'], $media_id);
				return '';
			} else return $this->respImage($media_id);
			exit;
		}
	}

	private function createPoster($fans, $poster)
	{
		global $_W;
		$bg = $poster['bg'];
		$pid = $poster['id'];
		$share = pdo_fetch('select * from ' . tablename($this->modulename . "_user") . " where uid='{$fans['uid']}' limit 1");
		if (empty($fans['uid']) || $fans['uid'] == 0) {
			$this->postText($this->message['from'], '对不起，您需要重新关注公众号才能参加活动！');
			exit;
		}
		if (empty($share)) {
			pdo_insert($this->modulename . "_user", array('uid' => $fans['uid'], 'nickname' => $fans['nickname'], 'avatar' => $fans['avatar'], 'pid' => $poster['id'], 'updatetime' => time(), 'createtime' => time(), 'vtime' => time(), 'ctime' => time(), 'parentid' => 0, 'uniacid' => $_W['uniacid'], 'score' => $poster['score'], 'cscore' => $poster['cscore'], 'from_user' => $this->message['from'], 'openid' => $this->message['from'], 'follow' => 1));
			$share['id'] = pdo_insertid();
			$share = pdo_fetch('select * from ' . tablename($this->modulename . "_user") . " where id='{$share['id']}'");
			mc_credit_update($fans['uid'], 'credit1', $poster['score'], array($fans['uid'], '首次制作海报送积分'));
		} else pdo_update($this->modulename . "_user", array('updatetime' => time()), array('id' => $share['id']));
		$this->postText($this->message['from'], '');
		$qrcode = str_replace('#sid#', $share['id'], IA_ROOT . $this->Qrcode);
		$data = json_decode(str_replace('&quot;', "'", $poster['data']), true);
		include 'makehaibao.php';
		set_time_limit(0);
		@ini_set('memory_limit', '512M');
		$size = getimagesize(tomedia($bg));
		$target = imagecreatetruecolor($size[0], $size[1]);
		$bg = imagecreates(tomedia($bg));
		imagecopy($target, $bg, 0, 0, 0, 0, $size[0], $size[1]);
		imagedestroy($bg);
		foreach ($data as $value) {
			$value = trimPx($value);
			if ($value['type'] == 'qr') {
				if ($poster['type'] == 2) {
					$url = $this->getQR($fans, $poster, $share['id']);
				} elseif ($poster['type'] == 3) {
					$url = $_W['siteroot'] . str_replace('./', 'app/', $this->createMobileurl('index', array('uniacid' => $_W['uniacid'], 'uid' => $fans['uid'])));
				}
				if (!empty($url)) {
					$img = IA_ROOT . "/addons/bsht_tbk/temp_qrcode.png";
					include "phpqrcode.php";
					$errorCorrectionLevel = "L";
					$matrixPointSize = "4";
					QRcode::png($url, $img, $errorCorrectionLevel, $matrixPointSize, 2);
					mergeImage($target, $img, array('left' => $value['left'], 'top' => $value['top'], 'width' => $value['width'], 'height' => $value['height']));
					@unlink($img);
				}
				$this->postText($this->message['from'], '');
			} elseif ($value['type'] == 'img') {
				$img = saveImage($fans['avatar']);
				mergeImage($target, $img, array('left' => $value['left'], 'top' => $value['top'], 'width' => $value['width'], 'height' => $value['height']));
				@unlink($img);
			} elseif ($value['type'] == 'name') {
				if (empty($value['size'])) {
					$value['size'] = '16px';
				}
				if (empty($value['color'])) {
					$value['color'] = '#000000';
				}
				mergeText($this->modulename, $target, $fans['nickname'], array('size' => $value['size'], 'color' => $value['color'], 'left' => $value['left'], 'top' => $value['top']), $poster);
			}
			$this->postText($this->message['from'], '');
		}
		imagejpeg($target, $qrcode);
		imagedestroy($target);
		return $qrcode;
	}

	private function getQR($fans, $poster, $sid)
	{
		global $_W;
		$modulename = 'bsht_tbk';
		$pid = $poster['id'];
		$qrtype = $poster['rtype'];
		$share = pdo_fetch('select * from ' . tablename($modulename . "_user") . " where id='{$sid}'");
		if (!empty($share['url'])) {
			$out = false;
			if ($qrtype == 1) {
				$qrcode = pdo_fetch('select * from ' . tablename('qrcode') . " where uniacid='{$_W['uniacid']}' and ticket='{$share['ticketid']}' " . " and name='{$poster['title']}' and url='{$share['url']}'");
				if ($qrcode['createtime'] + $qrcode['expire'] < time()) {
					pdo_delete('qrcode', array('id' => $qrcode['id']));
					$out = true;
				}
			}
			if (!$out) {
				return $share['url'];
			}
		}
		if (!$qrtype || $qrtype == 0) {
			$barcode['action_info']['scene']['scene_str'] = $modulename . $sid;
		} else {
			$sceneid = pdo_fetchcolumn('select qrcid from ' . tablename("qrcode") . " where uniacid='{$_W['uniacid']}' order by qrcid desc limit 1");
			if (empty($sceneid)) $sceneid = 1; else $sceneid++;
			$barcode['action_info']['scene']['scene_id'] = $sceneid;
		}
		load()->model('account');
		$acid = pdo_fetchcolumn('select acid from ' . tablename('account') . " where uniacid={$_W['uniacid']}");
		$uniacccount = WeAccount::create($acid);
		$time = 0;
		if ($qrtype == 1) {
			$barcode['action_name'] = 'QR_SCENE';
			$barcode['expire_seconds'] = 30 * 24 * 3600;
			$res = $uniacccount->barCodeCreateDisposable($barcode);
			$time = $barcode['expire_seconds'];
		} else {
			$barcode['action_name'] = 'QR_LIMIT_STR_SCENE';
			$res = $uniacccount->barCodeCreateFixed($barcode);
		}
		$rid = $this->rule;
		$sql = "SELECT * FROM " . tablename('rule_keyword') . " WHERE `rid`=:rid LIMIT 1";
		$row = pdo_fetch($sql, array(':rid' => $rid));
		$qrcode = array('uniacid' => $_W['uniacid'], 'acid' => $acid, 'name' => $poster['title'], 'keyword' => $row['content'], 'ticket' => $res['ticket'], 'expire' => $time, 'createtime' => time(), 'status' => 1, 'url' => $res['url']);
		if (!$qrtype || $qrtype == 0) {
			$qrcode['scene_str'] = $barcode['action_info']['scene']['scene_str'];
			$qrcode['model'] = 2;
			$qrcode['type'] = 'scene';
		} else {
			$qrcode['qrcid'] = $sceneid;
			$qrcode['model'] = 1;
		}
		pdo_insert('qrcode', $qrcode);
		pdo_update($modulename . "_user", array('sceneid' => $sceneid, 'ticketid' => $res['ticket'], 'url' => $res['url'], 'nickname' => $fans['nickname'], 'avatar' => $fans['avatar']), array('id' => $sid));
		return $res['url'];
	}

	private function getQR_old($fans, $poster, $sid)
	{
		global $_W;
		$pid = $poster['id'];
		if (empty($this->sceneid)) {
			$share = pdo_fetch('select * from ' . tablename($this->modulename . "_user") . " where id='{$sid}'");
			if (!empty($share['url'])) {
				$out = false;
				if ($poster['rtype']) {
					$qrcode = pdo_fetch('select * from ' . tablename('qrcode') . " where uniacid='{$_W['uniacid']}' and qrcid='{$share['sceneid']}' " . " and name='{$poster['title']}' and ticket='{$share['ticketid']}' and url='{$share['url']}'");
					if ($qrcode['createtime'] + $qrcode['expire'] < time()) {
						pdo_delete('qrcode', array('id' => $qrcode['id']));
						$out = true;
					}
				}
				if (!$out) {
					$this->sceneid = $share['sceneid'];
					return $share['url'];
				}
			}
			$this->sceneid = pdo_fetchcolumn('select sceneid from ' . tablename($this->modulename . "_user") . " where uniacid='{$_W['uniacid']}' order by sceneid desc limit 1");
			if (empty($this->sceneid)) $this->sceneid = 70000001; else $this->sceneid++;
			$barcode['action_info']['scene']['scene_id'] = $this->sceneid;
			load()->model('account');
			$acid = pdo_fetchcolumn('select acid from ' . tablename('account') . " where uniacid={$_W['uniacid']}");
			$uniacccount = WeAccount::create($acid);
			$time = 0;
			if ($poster['rtype']) {
				$barcode['action_name'] = 'QR_SCENE';
				$barcode['expire_seconds'] = 30 * 24 * 3600;
				$res = $uniacccount->barCodeCreateDisposable($barcode);
				$time = $barcode['expire_seconds'];
			} else {
				$barcode['action_name'] = 'QR_LIMIT_SCENE';
				$res = $uniacccount->barCodeCreateFixed($barcode);
			}
			$rid = $this->rule;
			$sql = "SELECT * FROM " . tablename('rule_keyword') . " WHERE `rid`=:rid LIMIT 1";
			$row = pdo_fetch($sql, array(':rid' => $rid));
			pdo_insert('qrcode', array('uniacid' => $_W['uniacid'], 'acid' => $acid, 'qrcid' => $this->sceneid, 'name' => $poster['title'], 'keyword' => $row['content'], 'model' => 1, 'ticket' => $res['ticket'], 'expire' => $time, 'createtime' => time(), 'status' => 1, 'url' => $res['url']));
			pdo_update($this->modulename . "_user", array('sceneid' => $this->sceneid, 'ticketid' => $res['ticket'], 'url' => $res['url'], 'nickname' => $fans['nickname'], 'avatar' => $fans['avatar']), array('id' => $sid));
			return $res['url'];
		}
	}

	public function postText($openid, $text)
	{
		$post = '{"touser":"' . $openid . '","msgtype":"text","text":{"content":"' . $text . '"}}';
		$ret = $this->postRes($this->getAccessToken(), $post);
		return $ret;
	}

	private function postRes($access_token, $data)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={$access_token}";
		load()->func('communication');
		$ret = ihttp_request($url, $data);
		$content = @json_decode($ret['content'], true);
		return $content['errcode'];
	}

	private function PostNews($poster, $name)
	{
		$stitle = unserialize($poster['stitle']);
		if (!empty($stitle)) {
			$thumbs = unserialize($poster['sthumb']);
			$sdesc = unserialize($poster['sdesc']);
			$surl = unserialize($poster['surl']);
			foreach ($stitle as $key => $value) {
				if (empty($value)) continue;
				$response[] = array('title' => str_replace('#昵称#', $name, $value), 'description' => $sdesc[$key], 'picurl' => tomedia($thumbs[$key]), 'url' => $this->buildSiteUrl($surl[$key]));
			}
			if ($response) return $this->respNews($response);
		}
		return '';
	}

	private function getAccessToken()
	{
		global $_W;
		load()->model('account');
		$acid = $_W['acid'];
		if (empty($acid)) {
			$acid = $_W['uniacid'];
		}
		$account = WeAccount::create($acid);
		$token = $account->getAccessToken();
		return $token;
	}

	private function emoji($str)
	{
		$str = json_encode($str);
		$str = preg_replace("#(\\\ud[0-9a-f]{3})#ie", "", $str);
		$str = preg_replace("#(\\\u2[0-9a-f]{3})#ie", "", $str);
		$str = preg_replace("#(\\\u0[0-9a-f]{3})#ie", "", $str);
		$str = json_decode($str);
		$str = trim(str_replace(array(' ', "'", ',', '。', '•', '.', '+', ')', '(', '_', '、', '，', '"'), '', $str));
		return $str;
	}

	private function nbnum()
	{
		srand((double)microtime() * 1000000);
		$ychar = "0,1,2,3,4,5,6,7,8,9";
		$listnum = explode(",", $ychar);
		for ($i = 0; $i < 6; $i++) {
			$randnum = rand(0, 9);
			$authnum .= $listnum[$randnum];
		}
		$nbnum = $authnum;
		return $nbnum;
	}

	private function nbqdreplace($string)
	{
		global $_W, $member, $fans, $settings;
		$nbindexurl = "<a href='" . $_W['siteroot'] . str_replace('./', 'app/', $this->createMobileurl('index')) . "'>点击这里</a>";
		if (!empty($settings['nbqd_diyurl1'])) {
			$nbqd_diyurl1 = "<a href='" . $settings['nbqd_diyurl1'] . "'>点击这里</a>";
		}
		if (!empty($settings['nbqd_diyurl2'])) {
			$nbqd_diyurl2 = "<a href='" . $settings['nbqd_diyurl2'] . "'>点击这里</a>";
		}
		$string = str_replace('[昵称]', $fans['nickname'], $string);
		$string = str_replace('[总积分]', $_W['nbqd']['total'], $string);
		$string = str_replace('[签到总积分]', $_W['nbqd']['allnum'], $string);
		$string = str_replace('[签到积分]', $_W['nbqd']['number'], $string);
		$string = str_replace('[今天得分]', $_W['nbqd']['today'], $string);
		$string = str_replace('[当天签到量]', (int)$_W['nbqd']['todaycom']['a'], $string);
		$string = str_replace('[首次积分]', $settings['everyday'], $string);
		$string = str_replace('[续签积分]', $settings['continuity'], $string);
		$string = str_replace('[积分上限]', $settings['intup'], $string);
		$string = str_replace('[模块首页]', $nbindexurl, $string);
		$string = str_replace('[自定义URL1]', $nbqd_diyurl1, $string);
		$string = str_replace('[自定义URL2]', $nbqd_diyurl2, $string);
		$string = str_replace('&lt;', '<', $string);
		$string = str_replace('&gt;', '>', $string);
		$aa = $_W['nbqd']['today'] + $settings['continuity'];
		if ((int)$settings['intup'] > 0 && $aa > (int)$settings['intup']) {
			$aa = (int)$settings['intup'];
		}
		$string = str_replace('[下期积分]', $aa, $string);
		return $string;
	}
}